﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
using UDS.Components;

namespace UDS.SubModule.UnitiveDocument
{
    /// <summary>
    /// MemberListView 的摘要说明。
    /// </summary>
    public partial class MemberListViewPage : Page
    {
        protected static string ClassID;
        protected static string DisplayType = "";
        protected static string Username;

        private void Page_Load(object sender, EventArgs e)
        {
            ClassID = (Request.QueryString["TeamID"] != null) ? Request.QueryString["TeamID"] : "";
            DisplayType = (Request.QueryString["DisplayType"] != null) ? Request.QueryString["DisplayType"] : "0";
            Username = SiteContext.Current.UserName;

            if (!IsPostBack)
            {
                BindGrid();
            }
        }

        private void btnLeader_Click(object sender, EventArgs e)
        {
            var team = new Team();
            bool sqlFlag = true;
            string sql = "";
            foreach (DataGridItem dgi in dgMemberList.Items)
            {
                var cb = (CheckBox)(dgi.Cells[0].Controls[1]);
                if (cb.Checked)
                {
                    int i = dgi.ItemIndex;
                    string id = dgMemberList.DataKeys[i].ToString();
                    if (sqlFlag)
                    {
                        sql += "" + id;
                        sqlFlag = false;
                    }
                    else
                    {
                        sql += " ,";
                        sql += id;
                    }
                }
            }
            //选择为空
            if (sql == String.Empty)
            {
                Response.Write("<script language=javascript>alert('请选择人员!');window.location='MemberListView.aspx?TeamID=" + ClassID + "';</script>");
            }
            else
            {
                if (cbRemind.Checked)
                    sms_all(2);
                if (team.SetLeader(sql, Int32.Parse(ClassID)))
                {
                    Response.Write("<script language=javascript>alert('设置组长成功!');window.location='MemberListView.aspx?TeamID=" + ClassID + "';</script>");
                }
                else
                {
                    Server.Transfer("../Error.aspx");
                }
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            var team = new Team();
            bool sqlFlag = true;
            string sql = "";
            foreach (DataGridItem dgi in dgMemberList.Items)
            {
                var cb = (CheckBox)(dgi.Cells[0].Controls[1]);
                if (cb.Checked)
                {
                    int i = dgi.ItemIndex;
                    string id = dgMemberList.DataKeys[i].ToString();
                    if (sqlFlag)
                    {
                        sql += "" + id;
                        sqlFlag = false;
                    }
                    else
                    {
                        sql += " ,";
                        sql += id;
                    }
                }
            }
            //选择为空
            if (sql == String.Empty)
            {
                Response.Write("<script language=javascript>alert('请选择人员!');window.location='MemberListView.aspx?TeamID=" + ClassID + "';</script>");
            }
            else
            {
                if (team.AddMemberToTeam(sql, Int32.Parse(ClassID)))
                {
                    if (cbRemind.Checked)
                        sms_all(1);
                    Response.Write("<script language=javascript>alert('加入成员至组成功!');window.location='MemberListView.aspx?TeamID=" + ClassID + "';</script>");
                }
                else
                {
                    Server.Transfer("../Error.aspx");
                }
            }
        }

        #region 数据绑定至DataGrid

        /// <summary>
        /// 将某用户的邮件取出绑定至DataGrid
        /// </summary>
        protected void BindGrid()
        {
            var team = new Team();
            var datatable = new DataTable();
            switch (DisplayType)
            {
                case "0":
                    datatable = Tools.ConvertDataReaderToDataTable(team.GetStaffInTeam(Int32.Parse(ClassID)));
                    btnAdd.Visible = false;
                    cmdDelete.Visible = true;
                    btnLeader.Visible = true;
                    break;
                case "1":
                    datatable = Tools.ConvertDataReaderToDataTable(team.GetStaffNotInTeam(Int32.Parse(ClassID)));
                    btnAdd.Visible = true;
                    cmdDelete.Visible = false;
                    btnLeader.Visible = false;
                    dgMemberList.Columns.Remove(dgMemberList.Columns[3]);
                    break;
                case "2":
                    datatable = Tools.ConvertDataReaderToDataTable(team.GetStaffSubscriptionTeam(Int32.Parse(ClassID)));
                    btnAdd.Visible = false;
                    cmdDelete.Visible = false;
                    btnLeader.Visible = false;
                    dgMemberList.Columns.Remove(dgMemberList.Columns[3]);
                    break;
                default:
                    break;
            }

            dgMemberList.DataSource = datatable.DefaultView;
            dgMemberList.DataBind();

            if (datatable.Rows.Count != 0)
            {
                cmdDelete.Attributes["onclick"] = "javascript:return confirm('您确认要选中的人员脱离组吗?');";
                btnLeader.Attributes["onclick"] = "javascript:return confirm('您确认要选中的人员设置为组长吗?');";
                btnAdd.Attributes["onclick"] = "javascript:return confirm('您确认要加入该成员吗?');";
            }
        }

        #endregion

        #region 翻页事件

        public void DataGrid_PageChanged(object sender, DataGridPageChangedEventArgs e)
        {
            dgMemberList.CurrentPageIndex = e.NewPageIndex;
            BindGrid();
        }

        #endregion

        #region Web Form Designer generated code

        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN：该调用是 ASP.NET Web 窗体设计器所必需的。
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// 设计器支持所需的方法 - 不要使用代码编辑器修改
        /// 此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.cmdDelete.Click += new System.EventHandler(this.cmdDelete_Click);
            this.btnLeader.Click += new System.EventHandler(this.btnLeader_Click);
            this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
            this.Load += new System.EventHandler(this.Page_Load);
        }

        #endregion

        #region 小组成员变化的消息通知函数 i为0表示脱离组,i为1表示加入组,i为2表示成为组长

        private void sms_all(int ii)
        {
            var list = Tools.FindSelectedItems(dgMemberList, item =>
            {
                var cb = (CheckBox)(item.Cells[0].Controls[1]);
                if (cb.Checked)
                {
                    return (int)dgMemberList.DataKeys[item.ItemIndex];
                }
                return null;
            });

            var sta = new Components.Staff();

            var staffList = Staff.GetAllStaff(false);
            var steam = new Team();
            using (SqlDataReader dr_allTeam = steam.GetStaffInTeam(Convert.ToInt32(ClassID))) //所有组员
            {
                string Team_name = ""; //项目名字
                string Staff_name = ""; //被选择人员名字
                string name_teamMaster = ""; //所有组长的名字

                var prj = new ProjectClass();
                using (SqlDataReader dr_allTeamMaster = prj.GetLeader(Convert.ToInt32(ClassID))) //所有组长
                {
                    using (SqlDataReader dataReader = prj.GetClassInfo(Convert.ToInt32(ClassID))) //项目信息
                    {
                        if (dataReader.Read())
                        {
                            Team_name = dataReader[0] + ",";
                        }
                    }

                    foreach (var s in staffList)
                    {
                        Staff_name += s.RealName + ",";
                    }

                    while (dr_allTeamMaster.Read())
                    {
                        name_teamMaster += dr_allTeamMaster["RealName"] + ",";
                    }
                }

                //处理短信提醒
                while (dr_allTeam.Read()) //i为0表示脱离组,i为1表示加入组,i为2表示成为组长
                {
                    switch (ii)
                    {
                        case 0:
                            SMS.SendMsg(Username, dr_allTeam["Staff_name"].ToString(), Team_name + " 项目处员工:" + Staff_name + "已经脱离本项目,特此通知.", SMSType.SiteMessage, DateTime.Now, "", 0, 0);
                            break;

                        case 1:
                            SMS.SendMsg(Username, dr_allTeam["Staff_name"].ToString(), "员工:" + Staff_name + "已经加入项目:" + Team_name + ",特此通知.", SMSType.SiteMessage, DateTime.Now, "", 0, 0);
                            break;

                        case 2:
                            SMS.SendMsg(Username, dr_allTeam["Staff_name"].ToString(), Team_name + " 项目处员工:" + Staff_name + "已经替代" + name_teamMaster + ",成为项目组长,特此通知.", SMSType.SiteMessage, DateTime.Now, "", 0, 0);
                            break;
                    }
                }
            }
        }

        #endregion

        #region 人员脱离

        private void cmdDelete_Click(object sender, EventArgs e)
        {
            var team = new Team();
            bool sqlFlag = true;
            string sql = "";
            foreach (DataGridItem dgi in dgMemberList.Items)
            {
                var cb = (CheckBox)(dgi.Cells[0].Controls[1]);
                if (cb.Checked)
                {
                    int i = dgi.ItemIndex;
                    string id = dgMemberList.DataKeys[i].ToString();
                    if (sqlFlag)
                    {
                        sql += "" + id;
                        sqlFlag = false;
                    }
                    else
                    {
                        sql += " ,";
                        sql += id;
                    }
                }
            }
            //选择为空
            if (sql == String.Empty)
            {
                Response.Write("<script language=javascript>alert('请选择人员!');window.location='MemberListView.aspx?TeamID=" + ClassID + "';</script>");
            }
            else
            {
                if (cbRemind.Checked)
                    sms_all(0);
                if (team.DeleteStaffFromTeam(sql, Int32.Parse(ClassID)))
                {
                    Response.Write("<script language=javascript>alert('人员脱离成功!');window.location='MemberListView.aspx?TeamID=" + ClassID + "';</script>");
                }
                else
                {
                    Server.Transfer("../Error.aspx");
                }
            }
        }

        #endregion

#if false
        #region 设置组长

        private void lnkbtnLeader_Click(object sender, EventArgs e)
        {
        }

        #endregion

        #region 加入成员至组

        private void lnkbtnAdd_Click(object sender, EventArgs e)
        {
        }

        #endregion
#endif
    }
}